<?php

namespace App\Http\Controllers;

use App\Notifications\FindPasswordNotify;
use App\User;
use Illuminate\Http\Request;

class PasswordController extends Controller
{
    // 填写找回密码的邮箱
    public function email()
    {
        return view('password.email');
    }

    // 发送邮件
    public function send(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|exists:users,email|email'
        ]);
        $user = User::where('email', $request->email)->first();
        $user->email_token = \Str::random(10);
        $user->save();
        \Notification::send($user, new FindPasswordNotify($user->email_token));
        return view('password.send');
    }

    // 编辑新的密码
    public function edit($token)
    {
        $user = $this->getUserByToken($token);
        return view('password.edit', compact('user'));
    }

    // 更新密码
    public function update(Request $request)
    {
        $this->validate($request, [
            'password' => 'required|min:6|confirmed'
        ]);
        $user = $this->getUserByToken($request->token);
        $user->password = bcrypt($request->password);
        $user->save();
        session()->flash('success', '密码重置成功！');
        return redirect()->to('login');

    }

    // 根据token获取用户
    public function getUserByToken($token)
    {
        return User::where('email_token', $token)->first();
    }
}
